package com.example.commons.config;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.example.commons.config.jwt.JwtBuild;
import com.example.commons.entity.Users;
import com.example.commons.exception.BusinessException;
import com.example.commons.util.PageConverterUtil;
import com.example.commons.util.TraceUtil;
import com.example.commons.util.UserUtil;
import com.example.commons.vo.CommonConstant;
import com.example.commons.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证token的拦截器
 */
@Slf4j
public class JwtFilter extends OncePerRequestFilter {
    JwtBuild jwtBuild = new JwtBuild(false, null);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        try {
            if (!ChainReleaseConfig.RELEASE_URL.contains(requestURI) && !requestURI.contains("private")) {

                String token = request.getHeader("token");
                if (StringUtils.isBlank(token)) {
                    throw new BusinessException("头部未携带token");
                }
                JwtBuild jwtBuild = new JwtBuild(false, null);
                String str = jwtBuild.getTokenData(token);
                Users user = JSONObject.parseObject(str, Users.class);
                UsernamePasswordAuthenticationToken userToken =
                        new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(userToken);
                request.setAttribute("login_data_bean", user);
                UserVo userVo = new UserVo();
                userVo.setId(Long.parseLong(user.getId()));
                userVo.setUsername(user.getUsername());
                UserUtil.put(userVo);
            }
            filterChain.doFilter(request, response);
        }catch (Exception e) {
                throw new BusinessException("认证失败");
            } finally {
            System.out.println("删除了副本");
                UserUtil.remove();
            MDC.remove(CommonConstant.TRACE_ID);
               // TraceUtil.remove();
            }
    }


}
